﻿#region Namespace
using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using FrameWorkMain;
using System.ServiceModel.Activation;
using LoginDetails;
using System.Web.Mail;
using System.Net.Mail;
using ebird.BusinessProcessAutomationDAS;
using ebird.eBirdGenerics;
using ebird.CaptchaGenerator;
using System.Diagnostics;
using System.Drawing;
using System.Drawing.Imaging;
using Eb.MessageBox;
#endregion

    public partial class Login : System.Web.UI.Page
    {
        private const string CAPTCHA_ID = "__CaptchaImage__";
        public string _result = "";
        #region Fields
        const int RATING1_MIN = 1;
        const int RATING1_MAX = 5;
        const int RATING2_MIN = 0;
        const int RATING2_MAX = 5;
        const int RATING3_MIN = 0;
        const int RATING3_MAX = 10;
        string connectionString = ConfigurationManager.ConnectionStrings["connectUserManager"].ToString();
        FrameWorkMain.FrameWorkMain frameWorkClass = new FrameWorkMain.FrameWorkMain();
        LoginDetails.CheckLogin loginCheck = new LoginDetails.CheckLogin();
        LoginDAS.Login loginDAS;
      //  ebird.ErrorHandlerHelper.ErrorLog errorLog;
        #endregion

  
        protected void Page_Load(object sender, EventArgs e)
        {
            
            if (Response.IsClientConnected)
            {
                //redirect the page Response.redirect(path);
            }
            if (Request.QueryString["captcha"] == "true")
                GetCaptchaImage();

          

            if (!IsPostBack)
            CreateCaptchaImage();
                // status = IsValidCaptcha();
           

            
          
            loginDAS = new LoginDAS.Login(connectionString);
           // errorLog = new ebird.ErrorHandlerHelper.ErrorLog();
           // Button1.Attributes.Add("Onclick", "getPrint('Print_All');");

            // btnForgotPwd.Attributes.Add("onClick", "javascript:window.open('ForgotPassword.aspx',null,'left=162px, top=134px, width=450px, height=500px, status=no, resizable= yes, scrollbars=yes, toolbar=no, location=no, menubar=no');");
        }
        #region Events
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnLogin_Click(object sender, EventArgs e)
        {
           // CreateCookie();
            System.Threading.Thread.Sleep(3000);
            DataSet loginDS = new DataSet();
            #region Fields
            int loginId = 0;
            int groupId = 0;
            #endregion
           
              //  bool status = loginCheck.ValidateLogin(txtLoginName.Text, txtPassword.Text, out loginDS);

                ///using 3 tier architecture

                bool status = loginDAS.ValidateLogin(txtLoginName.Text, txtPassword.Text, out loginDS);
                if (status)
                {
                    if (loginDS.Tables[0].Rows.Count > 0)
                    {
                        if (loginDS.Tables[0].Rows[0]["UD_UserPersonalID"].ToString() != "")
                            loginId = Convert.ToInt16(loginDS.Tables[0].Rows[0]["UD_UserPersonalID"].ToString());
                        if (loginDS.Tables[0].Rows[0]["US_GroupID"].ToString() != "")
                            groupId = Convert.ToInt16(loginDS.Tables[0].Rows[0]["US_GroupID"].ToString());
                    }
                    Session["UserId"] = loginId;
                    Session["UserGroupId"] = groupId;
                    Session["FirstName"] = loginDS.Tables[0].Rows[0]["UD_FirstName"].ToString();
                    Session["UserManager_Control"] = "TaskList.ascx";
                   Response.Redirect("~/BusinessProcessAutomation.aspx");
                   // Server.Transfer("~/BusinessProcessAutomation.aspx");
                }
                else
                {
                    MessageBox.Show("Invalid UserName/Password");
                   // lblLoginError.Visible = true;
                    //lblLoginError.Text = "Invalid UserName/Password";

                }
            //}
            //catch (Exception ex)
            //{

            //  //  CreateLogFiles.CreateLogFiles Err = new CreateLogFiles.CreateLogFiles();
            // //   Err.ErrorLog(Server.MapPath("Logs/ErrorLog"), ex.Message);

            //    //Using 3 tier
            //   // errorLog.LogWriter(Server.MapPath("Logs/ErrorLog"), ex.Message);

            //}
        }
        private bool ValidateUserCode(string userEnteredCode)
        {
            if (Session["Code"] != null)
            {
                if (Session["Code"].ToString().Equals(userEnteredCode))
                {
                    return true;
                }
                else
                {
                    // clear the session and generate a new code
                    Session["Code"] = null;
                    return false;
                    //Response.Write("the text u typed is incorrect please try again");
                }
            }
            else
            {
                return false;
            }
        }
        protected void btnSubmit_Click1(object sender, EventArgs e)
        {
            bool status;
            // lblShowPwd.Text = "test!!!!!!!!";
            try
            {
                if (txtCaptcha.Text.Trim() != "")
                {
                    status = ValidateUserCode(txtCaptcha.Text.Trim());
                  //  Captcha1.ValidateCaptcha(txtCaptcha.Text.Trim());
                    if (status)
                    {
                        string msg = string.Empty;
                        string from = string.Empty;
                        string pwd =string.Empty;
                        string to = "bindhya.c@ebirdonline.com";
                        pwd = loginCheck.GetPassword(txtUserName.Text, txtSecurityQuestion.Text, txtSAn.Text);
                        msg = "Your Password is " + pwd;
                        MailSender.SendEmail(from, pwd, to, "PassWord", msg, System.Web.Mail.MailFormat.Text, "");
                        lblShowPwd.Text = "";
                        lblShowPwd.Text = msg;
                    }
                    else
                    {
                        //CreateCaptchaImage();
                        lblShowPwd.ForeColor = System.Drawing.Color.Red;
                        lblShowPwd.Text = "InValid";
                    }

                }
                else
                {
                    //CreateCaptchaImage();
                    lblShowPwd.ForeColor = System.Drawing.Color.Red;
                    lblShowPwd.Text = "Fill all fields";
                }
                
            }
            catch (Exception ex)
            {
                lblShowPwd.Text = ex.Message;
            }


           // lblStatus.Text = "Sent email (" + txtSubject.Text + ") to " + txtTo.Text;





        }
        protected void hh_Click(object sender, EventArgs e)
        {

        }
        protected void RadioButtonList1_SelectedIndexChanged(object sender, EventArgs e)
        {
            // RoundedCornersExtender1.Radius = Convert.ToInt32(20);
        }
        protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
        {
            // RoundedCornersExtender1.Corners = (AjaxControlToolkit.BoxCorners)Enum.Parse(typeof(AjaxControlToolkit.BoxCorners), "All");
        }
        protected void Rating1_Changed(object sender, AjaxControlToolkit.RatingEventArgs e)
        {
            Evaluate_Rating1(int.Parse(e.Value));
        }
        #endregion
        #region Captcha
        // Generate a new CaptchaImage instance, with custom values
        private void CreateCaptchaImage()
        {

            CaptchaImage image = new CaptchaImage();
            Session[CAPTCHA_ID] = image;

            // customize CaptchaImage instance here
            image.CharacterSet = "BCDFGHJKLMNPQRSTVWXYZ";
        }

        /// <summary>
        /// Renders IMG SRC content for the client-side CAPTCHA image
        /// </summary>
        private void GetCaptchaImage()
        {
            CaptchaImage image = Session[CAPTCHA_ID] as CaptchaImage;
            Debug.Assert(image != null);
            Response.Clear();
            Response.ContentType = "image/jpeg";
            image.Image.Save(Response.OutputStream, ImageFormat.Jpeg);
        }
        private bool IsValidCaptcha()
        {
            CaptchaImage image = Session[CAPTCHA_ID] as CaptchaImage;
            return (String.Compare(image.Text, txtCaptcha.Text, true) == 0);
        }
        #endregion
        #region Methods
        public void Evaluate_Rating1(int value)
        {
            labelValue1.Text = EvaluateRating(value, Rating1.MaxRating, RATING1_MIN, RATING1_MAX);
        }
        public static string EvaluateRating(int value, int maximalValue, int minimumRange, int maximumRange)
        {
            int stepDelta = (minimumRange == 0) ? 1 : 0;
            double delta = (double)(maximumRange - minimumRange) / (maximalValue - 1);
            double result = delta * value - delta * stepDelta;
            return FormatResult(result);
        }
        public static string FormatResult(double value)
        {
            return String.Format("{0:g}", value);
        }
        protected bool tt1()
        {
            int i;
            return true;
        }
        #endregion
    }
